package com.whp.openapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whp.openapi.common.ResponseResult;
import com.whp.openapi.common.ResultTable;
import com.whp.openapi.dao.RoleMapper;
import com.whp.openapi.entity.Role;
import com.whp.openapi.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author whp
 * @date 2021/11/24
 */
@Service
public class RoleServiceImpl implements RoleService {
    
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public ResultTable getRolePageWithName(Integer page, Integer limit, String name) {
        //开启分页
        PageHelper.startPage(page, limit);
        //根据name查询
        List<Role> roles = roleMapper.getRoleWithName(name);
        PageInfo pi = new PageInfo(roles);
        //pi.getTotal()查询出的总条数  pi.getList()查询出的数据——>roles
        return new ResultTable(0, "", (int) pi.getTotal(), pi.getList());
    }
    
    @Override
    public ResponseResult updateStatus(Integer id, Integer status) {
        int i = roleMapper.updateByPrimaryKeySelective(new Role(id, status));
        if (i>0){
            return ResponseResult.getSuccess("状态修改成功！");
        }
        return ResponseResult.getFail("状态修改失败！");
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMapper.getRoleMenu(roleId);
    }
    
    @Override
    public ResponseResult assignMenu(Integer roleId, Integer[] menuIds) {
        //1.先删除中间表中的所有roleId的数据
        roleMapper.deleteMenuByRoleId(roleId);
        //2.批量新增menuIds数组中的数据
        roleMapper.insertMenus(roleId, menuIds);
        return ResponseResult.getSuccess();
    }

    @Override
    public ResponseResult addRole(Role role) {
        int i = roleMapper.insertSelective(role);
        if (i > 0) {
            return ResponseResult.getSuccess();
        }
        return ResponseResult.getFail("添加失败");
    }
    
    @Override
    public ResponseResult updateRole(Role role) {
        int i = roleMapper.updateByPrimaryKeySelective(role);
        if (i > 0) {
            return ResponseResult.getSuccess();
        }
        return ResponseResult.getFail("修改失败");
    }
}
